// Copyright 2007-2010 Comdiv (F. Sadykov) - http://code.google.com/u/fagim.sadykov/
// Supported by Media Technology LTD 
//  
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//  
//      http://www.apache.org/licenses/LICENSE-2.0
//  
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// 
// MODIFICATIONS HAVE BEEN MADE TO THIS FILE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using Comdiv.Application;
using Comdiv.Conversations;
using Comdiv.Design;
using Comdiv.Extensions;
using Comdiv.Inversion;
using Comdiv.Logging;
using NHibernate;
using NHibernate.Context;
using NHibernate.Engine;
using NHibernate.Impl;

namespace Comdiv.Persistence{
    public class TemporaryTransactionSession: ICanBeCommited{
        public ISession Session;
        private ISession oldtemporary;

        public TemporaryTransactionSession():this(myapp.ioc.get<ISessionFactoryProvider>().Get(null)){
            
        }
        public TemporaryTransactionSession(ISessionFactory factory){
            this.oldtemporary = AutomativeCurrentSessionContext.Temporary;
            Session = AutomativeCurrentSessionContext.Temporary = factory.OpenSession();
            Session.FlushMode = FlushMode.Never;
            Session.BeginTransaction();
        }

        public bool CanBeCommited { get; set; }
        public void Commit(){
            this.CanBeCommited = true;
        }

        public void Dispose(){
            if(Session.Transaction.IsActive){
                if (CanBeCommited)
                {
                    Session.Transaction.Commit();
                }
                else{
                    Session.Transaction.Rollback();
                }
            }
            AutomativeCurrentSessionContext.Temporary = oldtemporary;
        }
    }

    public class TemporarySimpleSession :ICanBeCommited
    {
        public ISession Session;
        private ISession oldtemporary;

        public TemporarySimpleSession()
            : this(myapp.ioc.get<ISessionFactoryProvider>().Get(null))
        {

        }
        public TemporarySimpleSession(ISessionFactory factory)
        {
            this.oldtemporary = AutomativeCurrentSessionContext.Temporary;
            Session = AutomativeCurrentSessionContext.Temporary = factory.OpenSession();
            Session.FlushMode = FlushMode.Never;
            
        }

        public bool CanBeCommited { get; set; }
        public void Commit()
        {
            this.CanBeCommited = true;
        }


        public void Dispose()
        {
            if (Session.Transaction.IsActive)
            {
                if (CanBeCommited)
                {
                    Session.Flush();
                }
            }
            Session.Close();
            AutomativeCurrentSessionContext.Temporary = oldtemporary;
        }
    }


    public class TemporaryReadonlySession
    {
        public ISession Session;
        private ISession oldtemporary;

        public TemporaryReadonlySession()
            : this(myapp.ioc.get<ISessionFactoryProvider>().Get(null))
        {

        }
        public TemporaryReadonlySession(ISessionFactory factory)
        {
            this.oldtemporary = AutomativeCurrentSessionContext.Temporary;
            Session = AutomativeCurrentSessionContext.Temporary = factory.OpenSession();
            Session.FlushMode = FlushMode.Never;
            Session.BeginTransaction();
        }

       

        public void Dispose()
        {
           
            Session.Transaction.Rollback();
            Session.Clear();
            Session.Close();
            AutomativeCurrentSessionContext.Temporary = oldtemporary;
        }
    }

    
    
    [DependOnService(typeof (IConversationManager))]
    public class AutomativeCurrentSessionContext : CurrentSessionContext, IConversationInterceptor{
        [ThreadStatic] private static ISession session;
        private ISession _single;
        public static string SessionCreatedEventName;
        private readonly ISessionFactoryImplementor factory;
        private bool conversationsInitialized = false;
        public ILog log = logger.get("comdiv.persistence.currentsession");
        private string theKey;

        public AutomativeCurrentSessionContext(ISessionFactoryImplementor factoryImplementor){
            factory = factoryImplementor;
            theKey = "current.session." + factory.Settings.SessionFactoryName;
        }

        public IConversationManager ConversationManager { get; set; }

        protected override ISession Session{
            get{
                lock (this){
                    return GetCurrentSession();
                }
            }
            set { }
        }

        #region IConversationInterceptor Members

        public int Idx { get; set; }

        public void Execute(ConversationLifeCycleStage stage, IConversation conversation){
            if (stage == ConversationLifeCycleStage.Finish){
                var sess = conversation.Data.get<ISession>(theKey);
                if (null != sess){
                    try{
                        if (sess.IsOpen){
                            if (sess.Transaction != null && sess.Transaction.IsActive){
                                sess.Transaction.Rollback();
                            }
                            sess.Close();
                        }
                    }
                    catch (Exception ex){
                        log.Error("cannot close session", ex);
                    }
                }
            }
        }

        #endregion

        public static IEnumerable<ISession> GetAllCurrentSessionsForConversation(IConversation conversation){
            foreach (var key in conversation.Data.Keys.Where(k => k.StartsWith("current.session."))){
                yield return conversation.Data.get<ISession>(key);
            }
        }

        private void checkInit(){
            if (!conversationsInitialized){
                conversationsInitialized = true;
                if (ConversationManager == null){
                    ConversationManager = myapp.conversation;
                }
                if (!ConversationManager.Interceptors.Contains(this)){
                    ConversationManager.Interceptors.Add(this);
                }
            }
        }

        public static void ClearLocalThreadSession(){
            session.free();
            session = null;
        }

        [ThreadStatic]internal static ISession Temporary;
        protected ISession GetCurrentSession(){
            checkInit();
            ISession result = null;

            //hack for temporary current
            if(Temporary!=null){
                return Temporary;
            }
            //HACK:for sql lite test
            if(useSingleSession){
                
                if(_single==null){
                    lock (this){
                        if(_single==null){
                            _single = newSession();
                        }
                    }
                }
                return _single;
            }

            result = GetByConversation();
            if (null != result){
                return result;
            }


            result = GetHttpContextSession();
            if (null != result){
                return result;
            }

            return LocalThreadSession();
        }

        public void Clean(){
            session.free();
            GetHttpContextSession(false).free();
        }

        private ISession LocalThreadSession(){
            lock (this){
                var slot = Thread.GetNamedDataSlot(theKey);
                var result = Thread.GetData(slot) as ISession;
                if (null == result || !result.IsOpen || ((SessionImpl)result).Factory!=this.factory){
                    Thread.SetData(slot, result = newSession());
                }
                
                return result;
            }
        }

        private ISession GetHttpContextSession(){
            return GetHttpContextSession(true);
        }


        private ISession GetHttpContextSession(bool create){
            var httpCurrent = HttpContext.Current;
            ISession result = null;
            if (null != httpCurrent){
                if (!httpCurrent.Items.Contains(theKey)){
                    if (!create){
                        return null;
                    }
                    result = newSession();
                    httpCurrent.Items[theKey] = result;
                }
                else{
                    result = (ISession) httpCurrent.Items[theKey];
                    if (!result.IsOpen){
                        if (create){
                            httpCurrent.Items[theKey] = result = newSession();
                        }
                    }
                }
            }
            return result;
        }


        private ISession newSession(){
            var result = factory.OpenSession();
            result.FlushMode = FlushMode.Commit;
            return result;
        }

        private ISession GetByConversation(){
            ISession result = null;
            if (null != ConversationManager){
                var current = ConversationManager.Current;
                if (null != current){
                    result = GetByConversation(current);
                }
            }
            return result;
        }

        private ISession GetByConversation(IConversation current){
            ISession result;
            result = current.Data.get<ISession>(theKey);
            if (null == result || !result.IsOpen){
                current.Data[theKey] = result = newSession();
                SessionCreatedEventName = "current session context : session created";
                //allow interceptors and other observers to react to new session creation
                ConversationManager.InvokeEvent(SessionCreatedEventName, current, result);
                if (current.istransactional()){
                    result.BeginTransaction();
                }
            }
            return result;
        }

        //HACK:for sql lite test
        private bool useSingleSession = false;
        [Hack]
        public void SingleSession(){
            useSingleSession = true;
        }
    }
}